//
//  AddressbookViewController.m
//  myhuibao
//
//  Created by li jun on 13-3-8.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "AddressbookViewController.h"
#import "BoxCell.h"
#import "config.h"
#import<QuartzCore/QuartzCore.h>
@interface AddressbookViewController ()

@end

@implementation AddressbookViewController
@synthesize mainTable;
@synthesize delegate;
@synthesize selectedIds;
@synthesize tvOther;
@synthesize other;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    tvOther.layer.cornerRadius=5;
    tvOther.layer.borderWidth=1;
    tvOther.layer.borderColor=[UIColor lightGrayColor].CGColor;
    tvOther.delegate = self;
    [self addCloseBar];
    tvOther.text=other;
    [self getSearchResult];
}

- (void)viewDidUnload
{
    [self setMainTable:nil];
    [self setTvOther:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void) getSearchResult{
    
    ABAddressBookRef addressBook =[self MyAddressBookCreate];
    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople (addressBook);
//    CFArrayRef allGroups = ABAddressBookCopyArrayOfAllGroups(addressBook);
    tableDataArray = [[NSMutableArray alloc] init];
    NSArray *ss = [selectedIds componentsSeparatedByString:@","];

    for (id person in (__bridge NSArray *) allPeople)
    {
        CFStringRef name = ABRecordCopyCompositeName((__bridge ABRecordRef)(person));

        //读取电话多值
        ABMultiValueRef phone = ABRecordCopyValue((__bridge ABRecordRef)(person), kABPersonPhoneProperty);
        for (int k = 0; k<ABMultiValueGetCount(phone); k++)
        {
            //获取电话Label
            NSString * personPhoneLabel = (NSString*)CFBridgingRelease(ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k)));
            //获取該Label下的电话值
            NSString * personPhone = (NSString*)CFBridgingRelease(ABMultiValueCopyValueAtIndex(phone, k));
            personPhone = [personPhone stringByReplacingOccurrencesOfString:@"(" withString:@""];
            personPhone = [personPhone stringByReplacingOccurrencesOfString:@")" withString:@""];
            personPhone = [personPhone stringByReplacingOccurrencesOfString:@"-" withString:@""];
            personPhone = [personPhone stringByReplacingOccurrencesOfString:@" " withString:@""];

            if([Config isMobileNumber:personPhone])
            {
//            NSLog(@"Person label: %@ phone:%@",personPhoneLabel, personPhone);
            NSMutableDictionary * address = [[NSMutableDictionary alloc] init];// [NSDictionary dictionaryWithObject:name  forKey:@"name"];
            [address setValue:(__bridge NSString*)name forKey:@"name"];
            [address setValue:personPhoneLabel forKey:@"label"];
            [address setValue:personPhone forKey:@"phone"];
            bool selected = [self isArray:ss contain:personPhone];
            if (selected)
                [address setValue:@"YES" forKey:@"checked"];
            else
                [address setValue:@"NO" forKey:@"checked"];
            [tableDataArray addObject:address];
            }
        }
    }
//    for (id group in (NSArray *) allGroups)
//    {
//        
//    }
//    CFRelease(allGroups);
    CFRelease(allPeople);
    CFRelease(addressBook);
//    NSLog(@"%@",tableDataArray);
    [mainTable reloadData];
    [Config setExtraCellLineHidden:mainTable];

}
- (bool)isArray:(NSArray *)a contain:(NSString*)s
{
    for(NSString *ss in a)
    {
        if ([s isEqualToString:ss]) {
            return true;
        }
    }
    return false;
}

#pragma 列表设置
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	int count = [tableDataArray count];
    return count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView widthForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 320;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"BoxCellIdentifier";
    
    BoxCell *cell = (BoxCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
    NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"BoxCell" owner:nil options:nil];
    cell = [array objectAtIndex:0];
    [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
            }
    
    NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
    cell.lbName.frame = CGRectMake(16,10,cell.lbName.frame.size.width,cell.lbName.frame.size.height);
    cell.lbName.text = [NSString stringWithFormat:@"%@-%@",[item valueForKey:@"name"],[item valueForKey:@"phone"]];
    cell.lbMemo.hidden = YES;
    cell.lbOther.hidden = YES;
    cell.imagepath = NULL;
    [cell.btnShowPhoto removeFromSuperview];
    //    cell.lbMemo.text = [item valueForKey:@"phone"];
    cell.checked = [[item valueForKey:@"checked"] boolValue];
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
    BOOL checked = [[item valueForKey:@"checked"] boolValue];
    BoxCell *cell = (BoxCell*)[tableView cellForRowAtIndexPath:indexPath];
    if (checked) {
        [cell setChecked:false];
        [item setValue:@"NO" forKey:@"checked"];

    }else{
        [cell setChecked:true];
        [item setValue:@"YES" forKey:@"checked"];

    }
	
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
    //其他cell的事件
    
}

- (IBAction)doBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
//    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)doSave:(id)sender {
    //判断手工输入是否为手机号码
    NSString* phones = tvOther.text;
    NSRange range = [phones rangeOfString:@"，"];
    if (range.location != NSNotFound) {
        UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                      message:@"请输入英文逗号。"
                                                     delegate:nil
                                            cancelButtonTitle:@"确定"
                                            otherButtonTitles:nil];
        [alert show];
        return;
    }

    NSArray *ss = [tvOther.text componentsSeparatedByString:@","];
    int othercount = ss.count;
    for(NSString *s in ss)
    {
        if ([s isEqualToString:@""]) {
            othercount--;
            continue;
        }
        if(![Config isMobileNumber:s])
        {
            UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                          message:@"请输入11位手机号码，并用逗号分开。"
                                                         delegate:nil
                                                cancelButtonTitle:@"确定"
                                                otherButtonTitles:nil];
            [alert show];
            return;
        }
    }

    NSString *ids=@"";
    NSString *names=@"";
    int selected=0;
    for(int i=0;i<tableDataArray.count;i++)
    {
        NSMutableDictionary *item = [tableDataArray objectAtIndex:i];
        BOOL checked = [[item valueForKey:@"checked"] boolValue];
        if(checked)
        {
            ids = [ids stringByAppendingFormat:@"%@,",[item valueForKey:@"phone"]];
            names = [names stringByAppendingFormat:@"%@,",[item valueForKey:@"name"]];
            selected++;
        }
    }
    if (othercount+selected>10) {
        UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                      message:@"最多只能发送10条短信。"
                                                     delegate:nil
                                            cancelButtonTitle:@"确定"
                                            otherButtonTitles:nil];
        [alert show];
        return;
    }
//    if(othercount+selected>0){
//        NSLog(@"%@", names);
        [delegate passNames:names withIds:ids withOther:tvOther.text];
        [self.navigationController popViewControllerAnimated:YES];

//    }
}
- (void)addCloseBar{
    UIToolbar * topView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
    [topView setBarStyle:UIBarStyleDefault];
    
    UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    UIBarButtonItem * doneButton = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(dismissKeyBoard)];
    NSArray * buttonsArray = [NSArray arrayWithObjects:btnSpace, doneButton, nil];
    
    [topView setItems:buttonsArray];
    [tvOther setInputAccessoryView:topView];
}
-(IBAction)dismissKeyBoard
{
    //    [commentDeatil resignFirstResponder];
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);
    self.view.frame = rect;
    [UIView commitAnimations];
    [tvOther resignFirstResponder];
}
- (void)textViewDidBeginEditing:(UITextView *)textView{
    float height = -250;
    CGRect frame = self.view.frame;
    frame.origin.y=height;
    [UIView beginAnimations:@"Curl"context:nil];//动画开始
    [UIView setAnimationDuration:0.30];
    [UIView setAnimationDelegate:self];
    [self.view setFrame:frame];
    [UIView commitAnimations];
//    if ([tvOther.text isEqualToString:@"其他号码，逗号分隔。"]) {
//        tvOther.text = @"";
//    }
}

-(ABAddressBookRef) MyAddressBookCreate
{
    ABAddressBookRef book = ABAddressBookCreateWithOptions(NULL, NULL);
    if (ABAddressBookGetAuthorizationStatus() != kABAuthorizationStatusAuthorized)
    {
        static NSCondition *_waiting;
        _waiting = [[NSCondition alloc] init];
        
        ABAddressBookRequestAccessWithCompletion(book, ^(bool granted, CFErrorRef error) {
            //[_waiting lock];
            [_waiting signal];
            //[_waiting unlock];
        });
        
        //[_waiting lock];
        [_waiting wait]; 
        //[_waiting unlock];
        _waiting = nil;
    }
    return book;
}
@end
